/**
* 首页js
*/

dms.index = {};
dms.index.init = function()
{	
	Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
	
	
	var leftPanel = new Ext.Panel(
	{
		region: 'west',
        id: 'dms-left',
        title: lang('folder tree'),
        split: true,
        width: 200,
        minSize: 120,
		autoScroll: true,
        maxSize: 400,
        collapsible: true,
		items:
		{
			xtype:'treepanel',
			dataUrl: dms.url.getFolderTree,
		    useArrows: false,
		    autoScroll: true,
		    animate: true,
		    border: false,
			rootVisible:true,
			lines:true,
			id:'useracl-tree',
			root: new Ext.tree.AsyncTreeNode(
			{
				text:'Root',
				id: './',
				expanded:true
			}),
			listeners: { click: dms.treeClick }
		}
	});
	
	
	new Ext.Viewport(
	{
		layout: 'border',
		id:'viewport',
		items: [
		{
			//用panel控件的底部工具栏当系统导航栏
			border:false,
			height:30,
			id:'dms-header',
			cls:'dms-header',
			contentEl:'dms-html-header',
			region:'north',
			margins:'0 0 0 0'
		}, 
		leftPanel ,
        new Ext.TabPanel({
            region: 'center',
			id:'dms-tabs',
            activeTab: 0,
			margins:'0 0 0 0',
            items:[
			{
				title: lang('file list'),
				layout: 'border',
				items: new Ext.grid.GridPanel(
				{
					clicksToEdit:2,
					id:'dms-grid',
					region: 'center',
					store: new Ext.data.Store(
					{
						remoteSort:false,
						proxy:new Ext.data.HttpProxy(
						{
							method:'POST',
							url: dms.url.getList
						}),
						reader:new Ext.data.JsonReader(
						{
							root:'root',
							idProperty:'name',
							totalProperty:'total',
							fields:['name','type','mtime']
						})
				    }),
			        columns: [
					{header: '' , width: 30, dataIndex: 'type',renderer: dms.renderer.icon },
					{
						id:'itemName',
						header: lang('file name'), 
						width: 160, 
						sortable: true, 
						dataIndex: 'name'
					},
					{header: lang('file type') , width: 100, sortable: true,  dataIndex: 'type'},
					{header: lang('mod time') , width:200, sortable:true,dataIndex:'mtime'}
			        ],
			        stripeRows: true,
			        autoExpandColumn: 'itemName',
					border:false,
					tbar:[
					{
						html: lang('current path')
					},
					{
						xtype: 'panel',
						html: 'Root/aaa/',
						id: 'current-path'
					}]
				})
		    }]
        })]
    });
	dms.clearLoading(500);
	dms.Tabs = Ext.getCmp('dms-tabs');
	dms.grid = Ext.getCmp('dms-grid');
	
	
	var toolbar = new Ext.Toolbar(
	{
		items:[
		{
			text: lang('new file'),
			iconCls: 'icon-add-file',
			handler: dms.handler.addFile
		},'-',
		{
			text: lang('new folder'),
			iconCls: 'icon-add-folder',
			handler: dms.handler.addFolder
		},'-',{
			text: lang('edit') ,
			id:'bt-edit',
			iconCls: 'icon-edit',
			disabled: true,
			handler: dms.handler.edit
		},'-',{
			text:lang('delete'),
			id:'bt-del',
			disabled: true,
			handler: dms.handler.del,
			iconCls: 'icon-del'
		},'-',
		{
			text:lang('refresh'),
			handler: dms.handler.refresh
		}]
	});

	toolbar.render(dms.grid.tbar);
	dms.grid.store.baseParams = { path: '' };
	
	dms.grid.getSelectionModel().addListener('selectionchange',function(sel)
	{
		if (sel.selections.items.length > 0)
		{
			Ext.getCmp('bt-edit').enable();
			Ext.getCmp('bt-del').enable();
		}
		else
		{
			Ext.getCmp('bt-edit').disable();
			Ext.getCmp('bt-del').disable();
		}
	});
	
	$.get('app/index/file_icons.json',function(data)
	{
		window.dms.fileIcons = data;
		window.dms.grid.store.load();
	},'json');
	
}

dms.renderer = {};
dms.renderer.icon = function(data)
{
	data = data.toLowerCase();
	var src = window.dms.fileIcons[data];
	if (!src) src = 'unknown.gif';
	return '<img src="app/index/file_icons/'+src+'" />';
}


/**
* tree的点击事件
*/
dms.treeClick = function(n)
{
	dms.grid.store.baseParams = { path:n.attributes.id };
	dms.currentPath = dms.grid.store.baseParams.path;
	dms.grid.store.load();
}



dms.closeCurrentTab = function()
{
	try
	{
		var t = dms.Tabs.getActiveTab();
		t.fireEvent('close');
		t.destroy();
	}
	catch(e){ }
}


/**
* 显示小提示
* param : text 文字
* param : time 时间(ms)
*/
dms.notify = function(text,time)
{
	if (!time) time = 2000;
	var div = $('#dms-notify-window').length > 0 ? $('#dms-notify-window') : $('<div id="dms-notify-window"></div>');
	try { clearTimeout(div.timer); } catch(e) { }
	div.stop().appendTo(document.body).html(text);
	div.css({ left: ($(window).width() - div.width())/2, top: ($(window).height() - div.height() - 100)/2 });
	div.fadeTo(200,0.95);
	div.timer = setTimeout(function()
	{
		div.animate(
		{
			opacity:0
			//bottom: -200
		},500,function()
		{
			div.remove();
		});
	},time);
}

/**
* 修改密码
*/
dms.changePassword = function(bt)
{
	(new Ext.Window(
	{
		title: lang('change password'),
		width: 300,
		height: 170,
		resizable: false,
		padding:10,
		id:'changePasswordWindow',
		animateTarget: bt,
		renderTo: Ext.getBody(),
		buttonAlign: 'center',
        modal: true,
		items: [
		{
			xtype:'form',
			id:'passwordForm',
			baseCls : 'x-plain',
			defaultType:'textfield',
			items:[
			{
				fieldLabel:lang('current password'),
				inputType:'password',
				name:'password',
				allowBlank:false
			},
			{
				fieldLabel:lang('new password'),
				inputType:'password',
				name:'newPassword',
				id: 'input-ps1',
				allowBlank:false
			},
			{
				fieldLabel:lang('retype password'),
				inputType:'password',
				name:'newPassword2',
				id: 'input-ps2',
				allowBlank:false
			}]
		}],
		buttons: [
		{
			text: lang('submit'),
			handler: function()
			{
				if ($('#input-ps1').val() != $('#input-ps2').val())
				{
					Ext.Msg.alert(lang('notice'),lang('passwords not match'));
					return;
				}
				Ext.getCmp('passwordForm').form.submit(
				{
					url : dms.url.changePassword,
					success : function(form, action)
					{
						dms.notify(lang('new password saved'));
						Ext.getCmp('changePasswordWindow').close();
					},
					failure : function(form, action)
					{
						Ext.Msg.alert(lang('notice'), lang(action.result.msg));
					},
					waitMsg : lang('submiting')
				});
			}
		},
		{
			text:lang('cancel'),
			handler: function()
			{
				Ext.getCmp('changePasswordWindow').close();
			}
		}]
	})).show();
}


/**
* 注销
*/
dms.logout = function()
{
	Ext.Msg.confirm(lang('notice'),lang('do you want to logout?'),function(bt)
	{
		if (bt == 'yes')
		{
			$.post(dms.url.logout,{  },function(data)
			{
				if (data.success)
				{
					window.location.reload();
				}
			},'json');
		}
	});
}

dms.handler = {};
dms.handler.edit = function()
{
	/*
		TODO 编辑文件
	*/
	var selected = dms.grid.getSelectionModel().getSelected();
	if (selected)
	{
		dms.addTab(
		{
			title:'编辑',
			js: ['app/editor/editor.js'],
			params: 
			{
				filename: selected.data.name,
				path: dms.currentPath
			}
		});
	}
}

dms.handler.del = function()
{
	var selected = dms.grid.getSelectionModel().getSelectedCell();
	if (selected)
	{
		var rowIndex = selected[0];
		var data = dms.grid.store.data.get(rowIndex);
		var path = dms.grid.store.baseParams.path;
		var fileName = data.json.name;
		$.post(dms.url.del,{ path: path + '/' + fileName },function(data)
		{
			if (data.success)
			{
				/*
					TODO 增加删除确认,只读文件确认，文件夹确认等
				*/
				dms.grid.store.removeAt(rowIndex);
				dms.notify(lang('deleted'));
			}
			else
			{
				Ext.Msg.alert(lang('error'),lang(data.msg));
			}
		},'json');
	}
}

dms.handler.addFolder = function()
{
	var r = new Ext.data.Record(
	{
		name: 'new folder',
		type: 'folder',
		mtime: '2010'
	});
	dms.grid.store.insert(0,r);
	dms.grid.getSelectionModel().select(0,0);
	/*
		TODO 新建文件夹的时候默认是编辑状态
	*/
}

dms.handler.refresh = function()
{
	dms.grid.store.reload();
}

dms.handler.addFile = function()
{
	var w = new Ext.Window(
	{
		title: lang('new file'),
		width: 300,
		//height:120,
		resizable: false,
		padding:10,
		id:'new_file_w',
		renderTo: Ext.getBody(),
		buttonAlign: 'center',
        modal: true,
		items: [
		{
			xtype:'form',
			id:'new_file_form',
			baseCls : 'x-plain',
			defaultType:'textfield',
			items:[
			{
				fieldLabel:lang('file name'),
				id:'new-file-name',
				name:'filename',
				allowBlank:false
			}]
		}],
		buttons: [
		{
			text: lang('submit'),
			handler: doNewFile
		},
		{
			text:lang('cancel'),
			handler: function()
			{
				Ext.getCmp('new_file_w').destroy();
			}
		}]
	});
	w.el.addKeyListener(13,function()
	{
		doNewFile();
	});
	w.show();
	setTimeout(function(){ $('#new-file-name').focus(); },200);
	
	function doNewFile()
	{
		var name = $('#new-file-name').val();
		if (name == '') return;
		$.post(dms.url.addFile,{ path:dms.currentPath, name:name },function(data)
		{
			if (data.success)
			{
				var r = new Ext.data.Record(
				{
					name: name,
					type: name.split('.').pop(),
					mtime: new Date().format('Y-m-d H:i:s')
				});
				dms.grid.store.insert(0,r);
				dms.grid.getSelectionModel().selectRow(0);
				w.destroy();
			}
			else
			{
				Ext.Msg.alert(lang('error'),lang(data.msg?data.msg:lang('add file error')));
			}
		},'json');
	}
}